<?php
class Messages extends Controller {

    function Messages() {
        parent::Controller();
        session_start();
        $this->load->model('municipalities_model');
        $this->lang->load("front");
        $this->load->library('email');
        $this->load->helper('my_language');
    }

    function index() {
        redirect(base_url().$this->lang->lang().'/municipality/chooseMunicipality', 'refresh');
    }

    function mail() {

        $this->email->to('dcizal@gmail.com');
        $this->email->from('darko@cizal.net');
        $this->email->subject('Here is your info ');
        $this->email->message('Hi. Here is the info you requested.');
        $this->email->send();
        echo $this->email->print_debugger();
    }

    function writeMessage($functionality_id=false,$representative_id=false,$edit_message=false) {
        if(!$this->session->userdata('municipality_id')) {
            redirect(base_url().$this->lang->lang().'/municipalities/chooseMunicipality', 'refresh');
        }
        if($functionality_id==false || $representative_id==false) {
            redirect(base_url().$this->lang->lang().'/representatives/pickRepresentative', 'refresh');
        }

        $this->lang->load('form_validation');
        $this->load->library('form_validation');
        $this->load->helper('role');
        $rules = $this->getRules();
        $this->form_validation->set_rules($rules);
        $fields['required']="<b>%s</b> ".$this->lang->language['form_validation_field_required'];
        $fields['valid_email']="<b>%s</b> ".$this->lang->language['form_validation_valid_email'];
        $fields['numeric']="<b>%s</b> ".$this->lang->language['form_validation_numeric'];
        $this->form_validation->set_message($fields);

        $this->load->model('municipalities_model');
        $this->load->model('representatives_model');
        
        if($representative_id=='all') {
            $curMunicipality = $this->getCurrentMunicipalityModel();
            switch ($functionality_id) {
                case "1":
                    $representatives = $this->representatives_model->getAllPratenici(get_language_id($this->lang->lang()),$curMunicipality[0]->izborna_edinica_id);
                    break;
                case "2":
                    $representatives = $this->representatives_model->getAllSovetnici(get_language_id($this->lang->lang()),$curMunicipality[0]->municipality_id);
                    break;
                case "3":
                    $representatives = $this->representatives_model->getAllGradonacalnici(get_language_id($this->lang->lang()),$curMunicipality[0]->municipality_id);
                    break;
            }
        }else{
           $representatives = $this->representatives_model->getRepresentativeByIdRS($representative_id);
           //$representatives = $representatives[0];
        }
        $data['allMunicipalities']=$this->municipalities_model->getAllMunicipalities(1);
        $data['representatives'] = $representatives;



        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);

        if ($this->form_validation->run() == FALSE) {
            $data['sendData']['role_id']=$functionality_id;
            $data['sendData']['rep_id']=$representative_id;
            if(sizeof($this->form_validation->_field_data)!=0) {
                $data['sendData'] = $this->transformData($this->form_validation->_field_data);
            }

            if($edit_message) {
                $data['sendData'] = $_SESSION['sendData'];
            }
            $content['middleFront'] = $this->load->view('write_message',$data,true);
        }
        else {
            $data['sendData'] = $_POST;
            $this->setSession($_POST);
            $munModel = $this->municipalities_model->getMunicipalityById($data['sendData']['municipality_id']);
            $data['municipality'] = $munModel[0];
            $content['middleFront'] = $this->load->view('preview_message',$data,true);
        }

        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);
    }

    function sendMessage() {
    //        var_dump($_SESSION['sendData']);
    //        die;
        if(isset($_SESSION['sendData'])) {

            $this->load->model('representatives_model');
            $this->load->model('messages_model');
            //            $this->load->model('rep_message_model');
            $this->load->helper('uniqueid');

            $messageData = array(
                "message" => $_SESSION['sendData']["message"],
                "sender_name" => $_SESSION['sendData']["sender_name"],
                "sender_address" => $_SESSION['sendData']["sender_address"],
                "sender_city" => $_SESSION['sendData']["sender_city"],
                "municipality_id" => $_SESSION['sendData']["municipality_id"],
                "sender_email" => $_SESSION['sendData']["sender_email"],
                "sender_phone" => $_SESSION['sendData']["sender_phone"]
            );

            $message_id = $this->messages_model->insertMessage($messageData);
            $message_tokken =uniqueid($message_id);

            if($_SESSION['sendData']['rep_id']=="all") {
            //Slucaj koga porakata se prakja na povekje lopovi
                $curMunicipality = $this->getCurrentMunicipalityModel();
                switch ($_SESSION['sendData']['role_id']) {
                    case "1":
                        $representatives = $this->representatives_model->getAllPratenici(get_language_id($this->lang->lang()),$curMunicipality[0]->izborna_edinica_id);
                        break;
                    case "2":
                        $representatives = $this->representatives_model->getAllSovetnici(get_language_id($this->lang->lang()),$curMunicipality[0]->municipality_id);
                        break;
                    case "3":
                        $representatives = $this->representatives_model->getAllGradonacalnici(get_language_id($this->lang->lang()),$curMunicipality[0]->municipality_id);
                        break;
                }
                //var_dump(sizeof($representatives));
                if(sizeof($representatives)>0) {
                    foreach ($representatives as $key=>$val) {
                        $rep_message_data = array(
                            "rep_id"=>$val->rep_id,
                            "message_id"=>$message_id,
                            "message_token"=>$message_tokken,
                            "message_status"=>0
                        );
                        $this->representatives_model->insertRepMessage($rep_message_data);
                    }
                }

            }else {
            //Slucaj koga porakata se prakja na eden lopov
                $rep_message_data = array(
                    "rep_id"=>$_SESSION['sendData']['rep_id'],
                    "message_id"=>$message_id,
                    "message_token"=>$message_tokken,
                    "message_status"=>0
                );
                $this->representatives_model->insertRepMessage($rep_message_data);
            }

            /*
             * Ako e seto ova uspesno vo toj slucaj treba da mu se prati mail na korisnikot
             * vo koj kje se generira link za potvrda na porakata(t.e validnosta na negoviot mail)
             * Od ovde treba da se redirectira na view(approveMessage) na koe kje mu se kaze na korinikot deka mu stignalo mail.
             * Pred da se napravi redirect treba da se iscisti sesijata.
             * Urlto sto treba da mu se prati na userot na mail treba da bide ova:
             * base_url().$this->lang->lang()."/messages/approvementProcess/".$_SESSION['sendData']['role_id']."/".$_SESSION['sendData']['rep_id']."/".$message_id."/".$message_tokken
             * Ova treba da bide obraboteno od approvementProcess
             */
            $this->email->to($messageData['sender_email']);
            $this->email->from('admin@pisiim.mk');
            $this->email->subject('Потврда за активација');
            $message = 'Почитувани, <br /><br />';
            $message .= 'За да ја потврдите активацијата ве молиме кликнете на следниот линк: <br />';
            $message .= base_url().$this->lang->lang()."/messages/approvementProcess/".$message_id."/".$message_tokken.'<br /><br />';  			$message .= 'Со почит, <br /> Pisiim.mk';
            $this->email->message($message);
            $this->email->send();
            redirect(base_url().$this->lang->lang()."/messages/approveMessage", 'refresh');
        // echo base_url().$this->lang->lang()."/messages/approvementProcess/".$message_id."/".$message_tokken;

        }
    }

    function qustionsAnswers($functionality_id=false,$representative_id=false) {
        if(!$this->session->userdata('municipality_id')) {
            redirect(base_url().$this->lang->lang().'/municipalities/chooseMunicipality', 'refresh');
        }
        if($functionality_id==false || $representative_id==false) {
            redirect(base_url().$this->lang->lang().'/representatives/pickRepresentative', 'refresh');
        }
        if($representative_id=="all") {
        //Ovde treba da se zemat prasanjata i dogovorite do/od site lopovi koi ja imaat konkretnata funkcija
        }else {
        //Zemi go lopovot so id $representative_id
        }

        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);
        $content['middleFront'] = $this->load->view('questions_answers',null,true);
        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);

    }

    function approveMessage($messageApproved=false) {
        if(isset($_SESSION['sendData'])) {
            unset($_SESSION['sendData']);
        }
        /*
         * Poradi toa sto koristam isto view(approve_message) pred da bide aktivirana i po aktiviranje na porakata
         * toa go kontoroliram so messageApproved koe e po default
         * false - pred da bide aktivirana porakata
         * true - otkatko kje bide aktivirana
        */
        $data['messageApproved'] = $messageApproved;
        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);
        $content['middleFront'] = $this->load->view('approve_message',$data,true);
        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);


    }

    function approvementProcess($message_id=false,$message_tokken=false) {
        //Ovde treba da se proveri koj e statusot na porakata. Ova treba da e mozno samo ako statusot e 0.
        //Bidejki ako porakata e vekje aktivirana (status 1) ili uste poloso vekje odobrena(status 2) dokolku pak
        //go poseti linkot sto mu e stignat na mail moze da go smeni statusot.
        if(!$message_id && !$message_tokken) {
            redirect(base_url().'mk/municipality/chooseMunicipality', 'refresh');
        }
        if(is_numeric($message_id)) {
            $condition = array(
                "message_id"=>$message_id,
                "message_token"=>$message_tokken
            );
            $field = array(
                "message_status" => 1
            );
            $this->load->model('rep_message_model');
            $this->rep_message_model->updateStatus($condition,$field);
            redirect(base_url().$this->lang->lang()."/messages/approveMessage/true", 'refresh');

        }else {
            redirect(base_url().$this->lang->lang().'/municipalities/chooseMunicipality', 'refresh');
        }
    }

    function representativeAnswer($rep_id,$message_id,$token) {
        $this->lang->load('form_validation');
        $this->load->library('form_validation');
        $this->load->helper('role');
        $rules = $this->getAnswerRules();
        $this->form_validation->set_rules($rules);
        $fields['required']="<b>%s</b> ".$this->lang->language['form_validation_field_required'];
        $fields['valid_email']="<b>%s</b> ".$this->lang->language['form_validation_valid_email'];
        $fields['numeric']="<b>%s</b> ".$this->lang->language['form_validation_numeric'];
        $this->form_validation->set_message($fields);
        $this->load->model('messages_model');
        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);

        if ($this->form_validation->run() == FALSE) {
            $result = $this->messages_model->checkRepresentativeAccess($rep_id,$message_id,$token);
            //Ovde treba da se proveri dali e vekje odgovorena porakata. Dali statusot i e 3.
            //Ako e 3 togas treba da redirektira na druga strana kaj so kje mu se kaze deka vekje odgovoril.
            if(sizeof($result>0)) {
                $data['sendData']['rep_id']=$rep_id;
                $data['sendData']['message_id']=$message_id;
                $data['sendData']['message_token']=$token;
                $data['sendData']['message']=$result[0]->message;
                $data['sendData']['sender_name']=$result[0]->sender_name;
                $data['sendData']['date_created']=$result[0]->date_created;


                $content['middleFront'] = $this->load->view('reprenetative_write_message',$data,true);

            }else {
                redirect(base_url().$this->lang->lang().'/municipalities/chooseMunicipality', 'refresh');
            }
        }
        else {
            $this->load->model('rep_message_model');
            $updateData = array(
                "answer_message"=>$_POST['answer_message'],
                "message_status"=>3
            );
            $condition = array(
                "message_id" => $_POST['message_id'],
                "rep_id" => $_POST['rep_id'],
                "message_token" => $_POST['message_token']
            );
            $this->rep_message_model->updateAnswer($condition,$updateData);
            //TODO Otkako kje se zapisat rabotive vo baza treba da mu se prati mail na userot na cie prasanje mu odgovoril re
            //representativot,deka ima odgovor i ne e loso da mu se prati link kade kje moze da go vidi toj odgovor.
            redirect(base_url().$this->lang->lang()."/messages/successAnswer", 'refresh');

        }

        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);
    }

    function successAnswer() {
        $content['head'] = $this->load->view('head',null,true);
        $content['header'] = $this->load->view('header',null,true);
        $content['middleFront'] = $this->load->view('success_answer',null,true);
        $content['footer'] = $this->load->view('footer',null,true);
        $this->load->view('index_front',$content);
    }

    function transformData($fieldArray) {
        $tArray = array();
        foreach ($fieldArray as $key=>$val) {
            $tArray[$key]=$val['postdata'];
        }
        return $tArray;
    }

    function setSession($arr) {
        unset($_SESSION['sendData']);
        $_SESSION['sendData'] = $arr;
    }

    function getCurrentMunicipalityModel() {
        $this->load->model('municipalities_model');
        $munModel = $this->municipalities_model->getMunicipalityById($this->session->userdata('municipality_id'));
        return $munModel;
    }

    function getAnswerRules() {
        $rules = array(
            array(
            'field'   => 'answer_message',
            'label'   => 'lang:the_answer',
            'rules'   => 'required|max_length[1000]'
            )
        );
        return $rules;
    }

    function getRules() {
        $rules = array(
            array(
            'field'   => 'message',
            'label'   => 'lang:message',
            'rules'   => 'required|max_length[1000]'
            ),
            array(
            'field'   => 'date_created',
            'label'   => 'lang:date_created',
            'rules'   => ''
            ),
            array(
            'field'   => 'sender_name',
            'label'   => 'lang:sender_name',
            'rules'   => 'required'
            ),
            array(
            'field'   => 'sender_address',
            'label'   => 'lang:sender_address',
            'rules'   => 'required'
            ),
            array(
            'field'   => 'sender_city',
            'label'   => 'lang:sender_city',
            'rules'   => 'required'
            ),
            array(
            'field'   => 'municipality_id',
            'label'   => 'lang:municipality_id',
            'rules'   => 'required'
            ),
            array(
            'field'   => 'sender_email',
            'label'   => 'lang:sender_email',
            'rules'   => 'required|valid_email'
            ),
            array(
            'field'   => 'sender_confirm_email',
            'label'   => 'lang:sender_confirm_email',
            'rules'   => 'required|valid_email'
            ),
            array(
            'field'   => 'sender_phone',
            'label'   => 'lang:sender_phone',
            'rules'   => ''
            )
        );
        return $rules;
    }



}
